package com.neusoft.common;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;

@Component
public class FTPUtil {
    private static String host;
    private static int port;
    private static String userName;
    private static String password;
    private static String remotePath;

    @Value("${ftp.host}")
    private void setHost(String host) {
        FTPUtil.host = host;
    }

    @Value("${ftp.port}")
    private void setPort(int port) {
        FTPUtil.port = port;
    }

    @Value("${ftp.username}")
    private void setUserName(String userName) {
        FTPUtil.userName = userName;
    }

    @Value("${ftp.password}")
    private void setPassword(String password) {
        FTPUtil.password = password;
    }


    @Value("${ftp.remotePath}")
    private void setRemotePath(String remotePath) {
        FTPUtil.remotePath = remotePath;
    }

    private static FTPClient getInstance(String workingDirectory) {
        //创建客户端
        FTPClient ftpClient = new FTPClient();
        //设置客户端编码
        ftpClient.setControlEncoding("UTF-8");
        try {
            // 连接客户端
            ftpClient.connect(host, port);
            // 登录客户端
            ftpClient.login(userName, password);
            //验证连接的返回值
            int replyCode = ftpClient.getReplyCode();
            //通过返回值判断是不是连接成功
            if (!FTPReply.isPositiveCompletion(replyCode)) {
                System.out.println("FTP服务连接失败");
                throw new Exception("FTP服务连接失败");
            }
            System.out.println("FTP服务（{}:{}）连接成功。" + host + ":" + port);

            // 设置文件上传格式，BINARY_FILE_TYPE 为二进制的
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
            // 创建文件保存路径
            ftpClient.makeDirectory(workingDirectory);
            // 设置文件上传路径
            ftpClient.changeWorkingDirectory(workingDirectory);
            // 设置连接模式（主动连接，被动连接）
            ftpClient.enterLocalPassiveMode();

        } catch (Exception e) {
            e.printStackTrace();
        }

        return ftpClient;
    }


    /**
     * 关闭客户端
     *
     * @param client
     */
    private static void close(FTPClient client) {
        if (null == client) {
            return;
        }

        try {
            client.logout();
        } catch (Exception e) {
            System.out.println("FTP退出登录失败。异常信息：{}");
        } finally {
            if (client.isConnected()) {
                try {
                    client.disconnect();
                    System.out.println("FTP断开连接成功。");
                } catch (Exception e) {
                    System.out.println("FTP断开连接失败。异常信息：{}");
                }
            }
        }
    }

    /**
     * 上传文件
     *
     * @param file 需要保存的文件
     * @return
     * @throws Exception
     */
    public static String upload(MultipartFile file) throws Exception {

        // 获取参数中的文件输入流
        InputStream inputStream = file.getInputStream();
        // 获取文件的名字
        String filename = file.getOriginalFilename();
        // 截取文件的后缀类型
        String suffix = filename.substring(filename.lastIndexOf("."));
        // 新文件的名字
        String newFileName = System.currentTimeMillis() + suffix;
        //  实例化FTP客户端
        FTPClient client = getInstance(remotePath);
        //  判断文件上传成功与否
        if (client.storeFile(newFileName, inputStream)) {
            System.out.println("上传文件{}成功。" + newFileName);
        } else {
            System.out.println("上传文件{}失败。" + "错误提示" + newFileName + client.getReplyString());
        }
        // 关闭FTP客户端连接
        close(client);
        // 关闭流
        inputStream.close();
        // 返回路径和文件名字
        return remotePath + newFileName;
    }

    /**
     * 文件下載
     * @param fileName
     * @param savePath
     * @return
     */
    public static boolean download(String fileName, String savePath) {
        //  实例化FTP客户端
        FTPClient client = getInstance(remotePath);
        File file = new File(savePath);
        //  定义字节流
        OutputStream os = null;
        try {
            //  实例化
             os = new FileOutputStream(file);
             client.retrieveFile(savePath,os);
        }catch (Exception e){

        }finally {
            try {
                // 关闭FTP客户端连接
                close(client);
                // 关闭流
                os.close();

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return true;
    }
}
